package be.kuleuven.thesis.pages;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import be.kuleuven.thesis.R;
import be.kuleuven.thesis.framework.Album;
import be.kuleuven.thesis.framework.AlbumListener;
import be.kuleuven.thesis.framework.Song;
import be.kuleuven.thesis.log.Logger;
import be.kuleuven.thesis.status.Player;
import be.kuleuven.thesis.status.PlaylistGenerator;
import be.kuleuven.thesis.status.StatusListener;

public class NowPlaying extends Activity implements StatusListener, AlbumListener{
	private Song currentSong;
	private Resources res;
	private Button playPause;
	private Button next;
	private Button previous;
	private Button radioOnButton;
	private SeekBar progressBar;
	private LinearLayout thumbsLayout;
	private ToggleButton thumbsUp;
	private Player player;
	private PlaylistGenerator generator;
	
	private final Handler handler = new Handler();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.now_playing);
        res = getResources();
        playPause = (Button) findViewById(R.id.play_button);
        next = (Button) findViewById(R.id.next_button);
        previous = (Button) findViewById(R.id.previous_button);
        progressBar = (SeekBar) findViewById(R.id.progress_bar);
        player = Player.getInstance();
        generator = PlaylistGenerator.getInstance();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		makeLayoutForCurrentStatus();
		player.registerStatusListener(this);
		generator.registerStatusListener(this);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		player.unRegisterListener(this);
		generator.unRegisterStatusListener(this);
	}
	
	private void makeLayoutForCurrentStatus() {
		currentSong = player.getCurrentSong();
		setTitleHeader();
		setOtherButtons();
        setAlbumCover();
        handleProgressBar();
        primarySeekBarProgressUpdater();
        handleBuffering();
        setMusicButtons();
	}
	
	private void setTitleHeader() {
		TextView title = (TextView) findViewById(R.id.header_title);
		TextView artist = (TextView) findViewById(R.id.header_artist);
		TextView album = (TextView) findViewById(R.id.header_album);
		if(currentSong != null) {
			title.setText(currentSong.getTitle());
			artist.setText(currentSong.getArtist());
			setAlbumInfo();
			//album.setText(currentSong.getAlbum().getName());
		}
		else {
			if(generator.isGenerating()) {
				title.setText("Generating...");
				album.setText("");
			}
			else if(!player.getCurrentPlaylist().isEmpty()) {
				title.setText("The current playlist has finished");
				album.setText("Press play to restart the current playlist");
			} else  {
				title.setText("No Song is currently playing");
				album.setText("");
			}
			artist.setText("");
		}
	}
	
	private void setAlbumInfo() {
		TextView albumText = (TextView) findViewById(R.id.header_album);
		if(currentSong.getAlbum() == null) {
			Album album = new Album(currentSong);
			album.registerListener(this);
			album.setMetaDataInThread();
			albumText.setText("");
		}
		else {
			if(currentSong.getAlbum().getName().equals(""))
				currentSong.getAlbum().registerListener(this);
				albumText.setText(currentSong.getAlbum().getName());
		}
	}
	
	private void setAlbumCover() {
		ImageView albumCover = (ImageView) findViewById(R.id.album_cover);
		albumCover.setImageDrawable(getCurrentCover());
	}
	
	private Drawable getCurrentCover() {
		if(currentSong == null || currentSong.getAlbum() == null || currentSong.getAlbum().getLargeImageUrl().equals("not found"))
			return null;
		if(currentSong.getAlbum().getImage() != null)
			return currentSong.getAlbum().getImage();
		else {
			currentSong.getAlbum().registerListener(this);
			currentSong.getAlbum().setAlbumCoverInThread();
		}
		return null;
	}
	
	private void setOtherButtons() {
		radioOnButton = (Button) findViewById(R.id.radio_on);
		thumbsLayout = (LinearLayout) findViewById(R.id.thumbs_buttons);
		thumbsUp = (ToggleButton) findViewById(R.id.thumbs_up);
		//Button thumbsDown = (Button) findViewById(R.id.thumbs_down);
		
		if(generator.isRadioOn()) {
			radioOnButton.setVisibility(Button.GONE);
			thumbsLayout.setVisibility(LinearLayout.VISIBLE);
			if(generator.isLiked(player.getCurrentSong()))
        		thumbsUp.setChecked(true);
        	else thumbsUp.setChecked(false);
		} else {
			radioOnButton.setVisibility(Button.VISIBLE);
			thumbsLayout.setVisibility(LinearLayout.GONE);
		}
		
		radioOnButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				generator.turnRadioOn();
				radioOnButton.setVisibility(Button.GONE);
				thumbsLayout.setVisibility(LinearLayout.VISIBLE);
				setTitleHeader();
				if(generator.isLiked(player.getCurrentSong()))
	        		thumbsUp.setChecked(true);
	        	else thumbsUp.setChecked(false);
			}
		});
		
		thumbsUp.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View view) {
				if(PlaylistGenerator.getInstance().isGenerating())
					return;
				Song song = player.getCurrentSong();
				if(generator.isLiked(song))
					generator.unlikeSong(song);
				else generator.likeSong(song);
			}
		});
		
//		thumbsDown.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View view) {
//				if(PlaylistGenerator.getInstance().isGenerating())
//					return;
//				generator.dislikeSong(player.getCurrentSong());
//				player.removeSong(player.getCurrentIndex());
//			}
//		});
	}
	
	private void handleProgressBar() {
		progressBar.setMax(99);
//		int progress = player.getCurrentPosition()/player.getCurrentSong().getDuration()*100;
//		progressBar.setProgress(progress);
		progressBar.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(player.isPlaying()) {
					player.setMediaToPosition(((SeekBar) v).getProgress());
					handleBuffering();
				}
				return false;
			}
		});
	}
	
	private void primarySeekBarProgressUpdater() {
		if(player.isBuffering())
			progressBar.setProgress(0);
		else {
			int progress = (int) (((float)player.getCurrentPosition()/player.getMediaFileLengthInMilliseconds())*100);
			progressBar.setProgress(progress);
		}
		if(player.isPlaying()) {
			Runnable notification = new Runnable() {
				public void run() {
					if(player.getCurrentSong() != null)
						primarySeekBarProgressUpdater();
				}
			};
			handler.postDelayed(notification, 1000);
		}
	}
	
	private void setMusicButtons() {
		if(player.getCurrentSong() == null)
			previous.setBackgroundDrawable(res.getDrawable(R.drawable.previous_black));
		else previous.setBackgroundDrawable(res.getDrawable(R.drawable.previous_button));
		
		if(player.isPlaying())
			playPause.setBackgroundDrawable(res.getDrawable(R.drawable.pause_button));
		else if(!player.getCurrentPlaylist().isEmpty())
			playPause.setBackgroundDrawable(res.getDrawable(R.drawable.play_button));
		else playPause.setBackgroundDrawable(res.getDrawable(R.drawable.play_button_black));
		
		if(player.getCurrentSong()==null)
			next.setBackgroundDrawable(res.getDrawable(R.drawable.next_black));
		else next.setBackgroundDrawable(res.getDrawable(R.drawable.next_button));
		
		previous.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(player.getCurrentSong() != null) {
					Player.getInstance().goToPrevious();
				}
			}
		});
		playPause.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(!player.isPlaying()) {
					player.resumePlay();
					Logger.getInstance().log("Player", "Play Resumed", player.getCurrentSong());
					primarySeekBarProgressUpdater();
					playPause.setBackgroundDrawable(res.getDrawable(R.drawable.pause_button));
				} else {
					player.pause();
					Logger.getInstance().log("Player", "Song Paused", player.getCurrentSong());
					playPause.setBackgroundDrawable(res.getDrawable(R.drawable.play_button));
				}
			}
		});
		next.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(Player.getInstance().canSkip()) {
					Logger.getInstance().log("Player","S Skipped("+player.getProgress()+"%)",player.getCurrentSong());
					Player.getInstance().skip();
				}
			}
		});
	}
	
	private void handleBuffering() {
		ProgressBar bufferSymbol = (ProgressBar) findViewById(R.id.buffer_symbol);
		TextView bufferText = (TextView) findViewById(R.id.buffer_text);
		if(player.isBuffering()) {
			bufferSymbol.setVisibility(ProgressBar.VISIBLE);
			bufferText.setVisibility(TextView.VISIBLE);
		} else {
			bufferSymbol.setVisibility(ProgressBar.GONE);
			bufferText.setVisibility(TextView.GONE);
		}
	}
	
	@Override
	public void onBackPressed() {
		GenerecsTabActivity.tabActivity.back();
		return;
	}

	@Override
	public void onCurrentSongChanged() {
		makeLayoutForCurrentStatus();
	}

	@Override
	public void onSongGenerated() {
		
	}
	
	@Override
	public void onSongRemoved() {
		makeLayoutForCurrentStatus();
	}

	@Override
	public void onPlaylistCleared() {
		
	}

	@Override
	public void onRadioSwitched() {
		
	}

	@Override
	public void onMediaPlayed() {
		primarySeekBarProgressUpdater();
		handleBuffering();
		makeLayoutForCurrentStatus();
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		progressBar.setSecondaryProgress(percent);
	}

	@Override
	public void onAlbumCoverSet() {
		setAlbumCover();
	}

	@Override
	public void onMetaDataSet(Album album) {
		setAlbumInfo();
		setAlbumCover();
	}

	@Override
	public void onNetworkProblem() {
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
	}

	@Override
	public void onFiltersTooTight() {
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.filters_severe), Toast.LENGTH_LONG).show();		
	}

	@Override
	public void onSongAdded() {
		
	}
}
